<?php

namespace App\Containers\AppSection\Signature\Tasks;

use App\Containers\AppSection\Signature\Data\Repositories\SignatureRepository;
use App\Containers\AppSection\Signature\Models\Signature;
use App\Ship\Cryptopro\CryptoCertificate;
use App\Ship\Exceptions\CreateResourceFailedException;
use App\Ship\Parents\Tasks\Task;
use Exception;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Str;

class CreateSignatureTask extends Task
{
    protected SignatureRepository $repository;
    protected Storage $storage;

    public function __construct(SignatureRepository $repository, Storage $storage)
    {
        $this->repository = $repository;
        $this->storage = $storage;
    }

    public function run(string $signature, CryptoCertificate $certificate, int $fileId, int $profileId, string $ts): Signature
    {

        try {
            $sigName = Str::uuid()->toString() . ".sig";
            $dir = config('filesystems.disks.' . config('filesystems.cloud') . '.dir');
            $path = $dir . '/' . Auth::id() . "/signatures/" . $fileId . "/" . $sigName;
            $isPut = $this->storage::disk(config('filesystems.cloud'))->put($path, $signature);
            if (!$isPut) {
                throw new Exception("Ошибка загрузки файла!");
            }

            return $this->repository->create([
                'file_id' => $fileId,
                'profile_id' => $profileId,
                'path' => $path,
                'issuer' => $certificate->Issuer,
                'subject' => $certificate->Subject,
                'signing_time' => $ts,
                'version' => $certificate->Version,
                'serial_number' => $certificate->SerialNumber,
                'thumbprint' => $certificate->Thumbprint,
                'valid_from' => $certificate->ValidFrom,
                'valid_to' => $certificate->ValidTo,
                'is_private' => $certificate->HasPrivate,
                'is_valid' => $certificate->IsValid,
            ]);
        } catch (Exception $exception) {
            throw new CreateResourceFailedException($exception->getMessage());
        }
    }
}
